<template>
  <div class="min-h-screen bg-[#FFFFFF] flex">
    <Nav></Nav>
    <div class="flex-1 p-8">
      <div class="bg-white rounded-lg shadow-sm p-6">
        <!-- 顶部标题和操作区 -->
        <div class="flex justify-between items-center mb-8">
          <h1 class="text-2xl font-medium text-gray-900">学生</h1>
          <el-button type="primary" class="flex items-center" @click="handleAddStudent">
            <el-icon class="mr-1"><Plus /></el-icon>
            添加学生
          </el-button>
        </div>

        <!-- 学生列表 -->
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
          <!-- 学生卡片 -->
          <div v-for="student in students" :key="student.id" 
          class="bg-white rounded-lg border border-gray-100 p-4 hover:shadow-md transition-shadow cursor-pointer relative"
          @click="handleEditStudent(student.id)">
              <!-- 优化设置默认按钮 -->
              <div 
                v-if="!student.is_default"
                @click.stop="handleSetDefault(student.id)"
                class="absolute top-2 right-2 w-6 h-6 flex items-center justify-center rounded-full bg-gray-50 hover:bg-blue-50 transition-colors cursor-pointer"
                :class="{'opacity-70 pointer-events-none': loading === student.id}" alt="点击设置当前学生">
                <el-icon v-if="loading === student.id" class="animate-spin text-blue-500"><Loading /></el-icon>
                <el-icon v-else class="text-gray-400 hover:text-blue-500"><Star /></el-icon>
              </div>
              <!-- 当前默认学生的黄色星星标识 -->
              <div 
                v-if="student.is_default"
                class="absolute top-2 right-2 w-8 h-8 flex items-center justify-center" alt="当前学生">
                <el-icon style="color: #FACC15; font-size: 20px;" alt="当前学生"><StarFilled /></el-icon>
              </div>
           <!-- 学生信息 -->
           <div class="flex items-center mb-4">
              <img :src="student.avatar_url || avatarDefault" 
                class="w-20 h-20 rounded-full mr-3" alt="头像">
              <div>
                <h3 class="text-lg font-medium text-gray-900">{{ student.username }}</h3>
                <p class="text-sm text-gray-500">{{ student.grade }}</p>
              </div>
            </div>
            <!-- 学生标签 -->
            <div class="flex gap-2 flex-wrap">
              <span v-if="student.is_default" 
                class="px-3 py-1 bg-green-100 text-green-800 text-xs rounded-full border border-green-200">
                <el-icon class="mr-1"><User /></el-icon>
                当前学生
              </span>
              <span :class="[
                'px-3 py-1 text-xs rounded-full border',
                student.sex === 1 
                  ? 'bg-blue-100 text-blue-800 border-blue-200' 
                  : 'bg-rose-100 text-rose-800 border-rose-200'
              ]">
                <el-icon class="mr-1" v-if="student.sex === 1"><Male /></el-icon>
                <el-icon class="mr-1" v-else><Female /></el-icon>
                {{ student.sex === 1 ? '男生' : '女生' }}
              </span>
              <span class="px-3 py-1 bg-indigo-100 text-indigo-800 text-xs rounded-full border border-indigo-200">
                <el-icon class="mr-1"><Notebook /></el-icon>
                {{ student.version }}
              </span>
            </div>
          </div>

          <!-- 添加学生卡片 -->
          <div @click="handleAddStudent" 
            class="bg-gray-50 rounded-lg border-2 border-dashed border-gray-200 p-4 flex flex-col items-center justify-center cursor-pointer hover:border-blue-400 transition-colors min-h-[160px]">
            <el-icon class="text-3xl text-gray-400 mb-2"><Plus /></el-icon>
            <span class="text-gray-500">添加学生</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import Nav from '@/components/nav/index.vue';
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus'; 
import { Plus, Check, Loading, Star,StarFilled } from '@element-plus/icons-vue';  // 图标
import { useRouter } from 'vue-router';
import { getUserInfo, clearUserInfo, setUserInfo } from "@/utils/auth";  // 添加 clearUserInfo, setUserInfo
import { User, Male, Female, Notebook } from '@element-plus/icons-vue';
import { setDefaultChild } from '@/api/student';
import { userApi } from '@/api';


const router = useRouter();
const students = ref([]);
// 添加 loading 状态
const loading = ref(null);
// 添加默认头像变量
const avatarDefault = new URL('@/assets/images/avatar/default.png', import.meta.url).href;

// 添加设置默认学生的方法
const handleSetDefault = async (id) => {
  try {
    loading.value = id;
    await setDefaultChild(id);
    
    // 重新获取用户信息并更新列表
    const userInfo = await userApi.getUserInfo();
    clearUserInfo();
    setUserInfo(userInfo);
    studentsData();
    
    ElMessage.success('设置成功');
  } catch (error) {
    ElMessage.error('设置失败');
  } finally {
    loading.value = null;
  }
};

// 添加编辑学生的方法
const handleEditStudent = (id) => {
  router.push(`/student/add?id=${id}`);
};

const handleAddStudent = () => {
  router.push('/student/add');
};

const studentsData = () => {
  const userInfo = getUserInfo();
  const children = userInfo.children || []; // Use .value to update ref
  students.value = children.map(child => ({
    id: child.id,
    username: child.username,
    grade: child.grade_name, // 转换年级值为可读名称
    avatar_url: import.meta.env.VITE_IMG_BASE_URL + child.avatar_url,
    is_default: child.is_default,
    version: child.version_name,
    sex: child.sex,
  }));

  // 打印学生信息
  console.log(userInfo.children);
};

onMounted(() => {
  studentsData(); 
});
</script>